const { MongoClient, GridFSBucket, ServerApiVersion } = require('mongodb')
let dayjs = require('dayjs')
const multer = require('multer')
const { Readable } = require('stream')
const express = require('express')
const app = express()

// MongoDB 连接信息
const uri = 'mongodb://localhost:27017/libraryDB'
const client = new MongoClient(uri, {
  serverApi: {
    version: ServerApiVersion.v1,
    strict: true,
    deprecationErrors: true,
  },
})

// 连接数据库
client
  .connect()
  .then(() => console.log('MongoDB Connected'))
  .catch((err) => console.log('MongoDB connection error:', err))

// 使用 multer 将文件存储到内存中
const storage = multer.memoryStorage()
const upload = multer({ storage })

// 文件上传的接口
const uploadFileToDB = async (req, res) => {
  try {
    // 通过 GridFS 存储上传的文件
    const db = client.db('libraryDB')
    const bucket = new GridFSBucket(db, {
      bucketName: 'files',
    })

    // 使用 multer 处理文件上传
    upload.single('file')(req, res, async (err) => {
      if (err) {
        return res.status(500).json({
          msg: '文件上传失败',
          success: false,
          error: err.message,
        })
      }

      const file = req.file // 获取上传的文件
      const readableStream = Readable.from(file.buffer)

      // 上传文件到 GridFS
      const uploadStream = bucket.openUploadStream(file.originalname, {
        metadata: {
          uploadedAt: dayjs().format(), // 上传时间
        },
      })

      readableStream.pipe(uploadStream)

      uploadStream.on('finish', () => {
        res.status(200).json({
          msg: '文件上传到服务器成功',
          time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
          msgCode: 10000,
          data: {
            success: true,
            fileId: uploadStream.id, // 返回文件的 _id
          },
        })
      })

      uploadStream.on('error', (error) => {
        res.status(500).json({
          msg: '文件上传失败',
          success: false,
          error: error.message,
        })
      })
    })
  } catch (error) {
    res.status(500).json({
      msg: '服务器异常',
      success: false,
      error: error.message,
    })
  }
}
module.exports = { uploadFileToDB }
